<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>WebSocket测试</title>
    <script type="text/javascript">
        class WS {

            constructor() {
                // 定时器ID用来执行网络重新链接
                this.intervalId = null;
                this.initConnect();
            }

            /**
             * 初始化链接配置
             */
            initConnect() {

                // 初始化 WebSocket 对象
                this.webSocket = new WebSocket(`ws://localhost:8080/websocket`);

                // 监听 WebSocket 连接异常的回调信息
                this.webSocket.onerror = (evt) => {
                    console.log('%c%s', 'color:red;', '=============连接异常=============');
                };

                // 监听 WebSocket 服务端未连接的回调信息
                this.webSocket.onclose = (evt) => {
                    console.log('%c%s', 'color:blue;', '=============网络连接已断开=============');
                    if (!this.intervalId) {
                        // 尝试重新链接
                        this.intervalId = setInterval(() => {
                            console.log('%c%s', 'color:blue;', '=============正在尝试重新连接=============');
                            this.initConnect();
                        }, 3000);
                    }
                }

                // 监听 WebSocket 连接成功的回调信息
                this.webSocket.onopen = (evt) => {
                    console.log('%c%s', 'color:purple;', '=============服务器已连接=============');
                    if (this.intervalId) {
                        // 服务器链接成功，清除重链定时器
                        window.clearInterval(this.intervalId);
                        this.intervalId = null;
                    }
                }

                // 监听 WebSocket 接收消息
                this.webSocket.onmessage = (evt) => {
                    this.onmessage(evt.data);
                }

            }

            /**
             * WebSocket 接收消息回调方法
             * @param msg
             */
            onmessage(msg) {
                document.body.innerText = msg
                console.log('%c%s', 'color:green;', msg);
                this.send(`你好我是 Client ${new Date().toLocaleString()}`);
            }

            /**
             * WebSocket 发送消息方法
             * @param callback
             */
            send(info) {
                this.webSocket.send(info);
            }

        }
    </script>
</head>
<body onload="new WS();">
</body>
</html>
